<?php
/**
 * UsersController.php
 *
 * PHP version 5
 *
 * LICENSE: This source file is subject to version 2.0 of the Apache license
 * that is available through the world-wide-web at the following URI:
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * @category Controller
 * @package  Controller
 * @author   Alex Kopp <koppa@rpi.edu>
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link     http://http://code.google.com/p/tri-chi/
 */

/**
 * UsersController
 *
 * The controller that manages the users that have access to use the
 * GLOrganizer system
 *
 * @category Controller
 * @package  Controller
 * @author   Alex Kopp <koppa@rpi.edu>
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link     http://http://code.google.com/p/tri-chi/
 */
class UsersController extends Controller
{
    public $layout='//layouts/main';
    
    /**
     * This is the list of filters we would like to enable for this controller.
     *
     * We want to limit access to this controller... Thus, including 'accessControl'
     *
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * 
     * Only administrators should be permitted to manage other Users
     * 
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
        array('allow', // allow administrators to perform all actions
                'actions'=>array('admin','delete','index','view','create','update'),
                'roles'=>array('admin'),
        ),
        array('deny',  // deny all actions to non-administrators
                'users'=>array('*'),
        ),
        );
    }

    /**
     * View Detailed Information about a User
     * 
     * @param string $id the username of the User to be displayed
     * 
     * @return void
     */
    public function actionView($id)
    {
        // Render the "view" view and pass along information about
        // the specified User
        $this->render(
            'view', array('model'=>$this->loadModel($id),)
        );
    }

    /**
     * Creates a new User.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * 
     * @return void
     */
    public function actionCreate()
    {
        $user=new Users;

        // AJAX Validation
        $this->performAjaxValidation($user);

        // If the form is submitted
        if (isset($_POST['Users'])) {
            // Sanitize and assign posted attributes to new User model.
            // Then, generate SHA1 hash of the desired password
            $user->attributes = $_POST['Users'];
            $user->password   = sha1($user->password);

            // Attempt to save (insert) new User into the database
            if ($user->save()) {
                // If successfully saved, redirect to the "view" page for
                // the new User
                $this->redirect(array('view','id'=>$user->username));
            }
        }

        $this->render(
            'create', array('model'=>$user, )
        );
    }

    /**
     * Updates a particular User.
     * If update is successful, the browser will be redirected to the 'view' page.
     * 
     * @param integer $id the username to be updated
     * 
     * @return void
     */
    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Users'])) {
            $oldEncryptedPassword = $model->password;
            $model->attributes=$_POST['Users'];
            if ($_POST['Users']['password'] != $oldEncryptedPassword) {
                //Changing Password. Must Convert to SHA1
                $model->password = sha1($_POST['Users']['password']);
            }
            //echo Yii::trace(CVarDumper::dumpAsString($model->password),'vardump');
            if ($model->save()) {
                $this->redirect(array('view','id'=>$model->username));
            }
        }

        $this->render(
            'update', array('model'=>$model,)
        );
    }

    /**
     * Deletes a particular user.
     * 
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * 
     * @param integer $id the username to be deleted
     * 
     * @return void
     */
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), don't
            // redirect the browser
            if (!isset($_GET['ajax'])) {
                $this->redirect(
                    isset($_POST['returnUrl'])
                    ? $_POST['returnUrl']
                    : array('admin')
                );
            }
        } else {
            throw new CHttpException(
                400, 'Invalid request. Please do not repeat this request again.'
            );
        }
    }

    /**
     * Lists all Users in the system.
     * 
     * @return void
     */
    public function actionIndex()
    {
        $model=new Users('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Users'])) {
            $model->attributes=$_GET['Users'];
        }
        
        $newModel = new Users;

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Users'])) {
            $newModel->attributes=$_POST['Users'];
            if ($newModel->validate()) {
                if ($newModel->save()) {
                    $this->redirect(array('view','id'=>$newModel->username));
                }
            }
        }

        $this->render(
            'index', array(
                'newModel'=>$newModel,
                'model'=>$model,
            )
        );
    }

    /**
     * Manages all Users.
     * 
     * @return void
     */
    public function actionAdmin()
    {
        $model=new Users('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Users'])) {
            $model->attributes=$_GET['Users'];
        }

        $this->render(
            'admin', array(
                'model'=>$model,
            )
        );
    }

    /**
     * Returns user information based on the username (primary key) given
     * in the GET variable. If the data model is not found, an HTTP
     * exception will be raised.
     * 
     * @param integer $id the username to be loaded
     * 
     * @return User
     */
    public function loadModel($id)
    {
        $model=Users::model()->findByPk($id);
        if ($model===null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * 
     * @param CModel $model the model to be validated
     * 
     * @return void
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax']==='users-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}
